<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" dir="ltr" lang="en"><head>
	<title>design:archive:model_view_controller_pattern [phpPatterns]</title>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	  <meta name="generator" content="DokuWiki snapshot?">
  <link rel="start" href="http://www.phppatterns.com/">
  <link rel="contents" href="http://www.phppatterns.com/docs/design/archive/model_view_controller_pattern?do=index" title="">
  <link rel="alternate" type="application/rss+xml" title="Recent Changes" href="http://www.phppatterns.com/feed.php">
  <link rel="alternate" type="application/rss+xml" title="Current Namespace" href="http://www.phppatterns.com/feed.php?mode=list&amp;ns=design:archive">
  <link rel="alternate" type="text/html" title="Plain HTML" href="http://www.phppatterns.com/docs/design/archive/model_view_controller_pattern?do=export_html">
  <link rel="alternate" type="text/plain" title="Wiki Markup" href="http://www.phppatterns.com/docs/design/archive/model_view_controller_pattern?do=export_raw">
  <link rel="stylesheet" media="screen" type="text/css" href="model_view_controller_pattern_files/style.css">
  <meta name="date" content="2005-10-15T21:47:50-0400">
  <meta name="robots" content="index,follow">
  <script src="model_view_controller_pattern_files/ga.js" async="" type="text/javascript"></script><script language="javascript" type="text/javascript" charset="utf-8">
    var alertText   = 'Please enter the text you want to format.\nIt will be appended to the end of the document.'
    var notSavedYet = 'Unsaved changes will be lost.\nReally continue?'
    var DOKU_BASE   = 'http://www.phppatterns.com/'
  </script>
  <script language="javascript" type="text/javascript" charset="utf-8" src="model_view_controller_pattern_files/script.js"></script>
  <script language="javascript" type="text/javascript" charset="utf-8" src="model_view_controller_pattern_files/tw-sack.js"></script>
  <script language="javascript" type="text/javascript" charset="utf-8" src="model_view_controller_pattern_files/ajax.js"></script>
  <script language="javascript" type="text/javascript" charset="utf-8" src="model_view_controller_pattern_files/domLib.js"></script>
  <script language="javascript" type="text/javascript" charset="utf-8" src="model_view_controller_pattern_files/domTT.js"></script>
  <link rel="stylesheet" type="text/css" href="model_view_controller_pattern_files/style_002.css">
	<link rel="shortcut icon" href="http://www.phppatterns.com/lib/tpl/phppatterns/images/favicon.ico">
	<link rel="stylesheet" media="screen" type="text/css" href="model_view_controller_pattern_files/layout.css">
	<link rel="stylesheet" media="screen" type="text/css" href="model_view_controller_pattern_files/design.css">
	<link rel="stylesheet" media="screen" type="text/css" href="model_view_controller_pattern_files/plugins.css">
	<link rel="stylesheet" media="print" type="text/css" href="model_view_controller_pattern_files/print.css">
	<link rel="stylesheet" media="screen" type="text/css" href="model_view_controller_pattern_files/sidebar.css">
	<link rel="stylesheet" media="screen" type="text/css" href="model_view_controller_pattern_files/roundcorners.css">
	<!--[if gte IE 5]>
	<style type="text/css">
	/* that IE 5+ conditional comment makes this only visible in IE 5+ */
	/* IE bugfix for transparent PNGs */
	//DISABLED   img { behavior: url("http://www.phppatterns.com/lib/scripts/pngbehavior.htc"); }
	</style>
	<![endif]-->
<script src="model_view_controller_pattern_files/gt.js" async="" type="text/javascript"></script></head>
<body>
<img src="model_view_controller_pattern_files/indexer.gif" alt="" width="1" height="1"><div class="dokuwiki">
	<div id="header">
		<div id="header_title">
			<div class="logo">
			<a href="http://www.phppatterns.com/docs/" name="top" accesskey="h" title="[ALT+H]">phpPatterns</a>			</div>
			<div class="pagename">
			[[<a href="http://www.phppatterns.com/docs/design/archive/model_view_controller_pattern?do=backlink">design:archive:model_view_controller_pattern</a>]]
			</div>
		</div>
		<div class="bar" id="header_bar">
			<div class="bar_left" id="bar_topleft">
				<form action="http://www.phppatterns.com/docs/" accept-charset="utf-8" class="search" name="search"><input name="do" value="search" type="hidden"><input id="qsearch_in" accesskey="f" name="id" class="edit" onkeyup="ajax_qsearch.call('qsearch_in','qsearch_out')" type="text"><input value="Search" class="button" type="submit"><div id="qsearch_out" class="ajax_qsearch" onclick="this.style.display='none'"></div></form>&nbsp;
			</div>
			<div class="bar_right" id="bar_topright">
												<form class="button" method="get" action="http://www.phppatterns.com/docs/design/archive/model_view_controller_pattern"><input name="do" value="login" type="hidden"><input value="Login" class="button" type="submit"></form>				<form class="button" method="get" action="http://www.phppatterns.com/docs/design/archive/model_view_controller_pattern"><input name="do" value="index" type="hidden"><input value="Index" class="button" title="ALT+X" accesskey="x" type="submit"></form>				<form class="button" method="get" action="http://www.phppatterns.com/docs/"><input name="do" value="recent" type="hidden"><input value="Recent changes" class="button" title="ALT+R" accesskey="r" type="submit"></form>			</div>
		</div>
	</div>
		<div id="content">
		<div id="page_buttons">
			<form class="button" method="post" action="http://www.phppatterns.com/docs/design/archive/model_view_controller_pattern"><input name="do" value="edit" type="hidden"><input name="rev" value="" type="hidden"><input value="Show pagesource" class="button" title="ALT+V" accesskey="v" type="submit"></form>			<form class="button" method="get" action="http://www.phppatterns.com/docs/design/archive/model_view_controller_pattern"><input name="do" value="revisions" type="hidden"><input value="Old revisions" class="button" title="ALT+O" accesskey="o" type="submit"></form>		</div>
		<div id="page" class="page">
						<div class="toc">
<div class="tocheader"> <script type="text/javascript">showTocToggle("+","-")</script><div class="toctoggle"><a href="javascript:toggleToc()" class="toc"><span id="showlink" style="display:none;"><img src="model_view_controller_pattern_files/arrow_down.gif" alt="+"></span><span id="hidelink"><img src="model_view_controller_pattern_files/arrow_up.gif" alt="-"></span></a></div>
Table of Contents</div>
<div id="tocinside">
<ul class="toc">
<li class="level1"><span class="li"><a href="#the_view" class="toc">The View</a></span></li>
<li class="level1"><span class="li"><a href="#the_model" class="toc">The Model</a></span></li>
<li class="level1"><span class="li"><a href="#the_controller" class="toc">The Controller</a></span></li>
<li class="level1"><span class="li"><a href="#an_example" class="toc">An Example</a></span></li>
</ul>
</div>
</div>

<p>
The MVC pattern very commonly used in constructing web applications. The
 principle allows us to construct 3-tier applications, allowing us 
useful layers of seperation in our code, and helping both designers and 
developers to cooperate as well enhancing our ability to maintain and 
expand on existing applications.
</p>

<p>
<a href="#fn1" name="fnt1" class="fn_top" onmouseover="fnt('1', this, event);">1)</a> 
</p>

<a name="the_view"></a><h1>The View</h1>
<div class="level1">

<p>
 “Views” are basically the end result which we send to a web browser - the <acronym title="HyperText Markup Language">HTML</acronym> generated by our script, for example. When talking about views, many people think of <a href="http://www.phppatterns.com/docs/design/templates_and_template_engines" class="wikilink1" title="design:templates_and_template_engines">template solutions</a> but whether it’s accurate to call a template engine a View is debatable.
</p>

<p>
Perhaps the key thing about Views is they should be “self aware”, in 
that as a View is rendered, elements of the view are aware of their role
 in the greater scheme of things. Taking <acronym title="Extensible Markup Language">XML</acronym> as the example, one might say that <acronym title="Extensible Markup Language">XML</acronym> parsed with the <acronym title="Document Object Model">DOM</acronym> <acronym title="Application Programming Interface">API</acronym> has this awareness - a node in a dom tree knows where it is and what it contains while nodes in an <acronym title="Extensible Markup Language">XML</acronym> document parsed with SAX have no understanding over themselves until the parser reaches them.
</p>

<p>
Most <acronym title="Hypertext Preprocessor">PHP</acronym> template solutions use some simplistic procedure language and certainly template tags used like this;
</p>
<pre class="code">&lt;p&gt;{some_text}&lt;/p&gt;
&lt;p&gt;{some_more_text}&lt;/p&gt;
</pre>

<p>
Have no understanding of the document they will become, what they represent and are simply there for <acronym title="Hypertext Preprocessor">PHP</acronym> to replace them with something else.
</p>

<p>
If you agree with this loose description of a View, you’ll also agree 
that most of the template engines fail to create the desired division 
between View and Model, the knowledge of what the template tags will 
become having to be stored within the Model.
</p>

<p>
Some questions to ask yourself when implementing Views: “How easy is it 
to make global changes to all views?”, “How long does it take to 
implement new views?”, “Can presentation language delivered by the View 
be easily interchanged with another (e.g. deliver a <acronym title="Simple Object Access Protocol">SOAP</acronym> document instead of an <acronym title="HyperText Markup Language">HTML</acronym> document from the same View).
</p>

</div>

<a name="the_model"></a><h1>The Model</h1>
<div class="level1">

<p>
 The Model represents application logic (often called the business layer in enterprise applications).
</p>

<p>
Generally speaking, it’s the job of the Model to transform raw data into
 data which contains some sort of meaning, which is then delivered to 
the View for display. Frequently the Model will encapsulate database 
queries, perhaps taking advantage of an abstract database class (a data 
access layer) to actually perform the queries.
</p>

<p>
For example, say you wanted to calculate the yearly rainfall in the 
United Kingdom (just to convince yourself there’s better places for a 
holiday), the Model would receive a set of daily rainfall figures for 
ten years then perform an average and deliver it to the View.
</p>

</div>

<a name="the_controller"></a><h1>The Controller</h1>
<div class="level1">

<p>
 The controller is basically the first point of call for any incoming <acronym title="Hyper Text Transfer Protocol">HTTP</acronym>
 requests in a web application. It examines what it received in the 
request, such as a collection of GET variables, as responds 
appropiately. You can hardly even begin coding <acronym title="Hypertext Preprocessor">PHP</acronym>
 without writing your first controller of some sort. The most common use
 is something like a switch() statement in your index.php such as;
</p>
<pre class="code">&lt;?php
switch ($_GET['viewpage']) {
    case "news":
        $page=new NewsRenderer;
    break;
    case "links":
        $page=new LinksRenderer;
    break;
    default:
        $page=new HomePageRenderer;
    break;
}
$page-&gt;display();
?&gt;
</pre>

<p>
That’s using a mix of procedural and object oriented code but for a 
small website, is frequently a perfectly valid choice. The above code 
could do better though.
</p>

<p>
The Controller is essentially the component which triggers the binding of data from the Model to elements in the View.
</p>

</div>

<a name="an_example"></a><h1>An Example</h1>
<div class="level1">

<p>
 Here’s a simple example of the MVC pattern in action.
</p>

<p>
First we need a data access layer, which is generic class;
</p>
<pre class="code php"><span class="kw2">&lt;?php</span>
<span class="coMULTI">/**
 *  A simple class for querying MySQL
 */</span>
<span class="kw2">class</span> DataAccess <span class="br0">{</span>
    <span class="coMULTI">/**
    * Private
    * $db stores a database resource
    */</span>
    <span class="kw2">var</span> <span class="re0">$db</span>;
    <span class="coMULTI">/**
    * Private
    * $query stores a query resource
    */</span>
    <span class="kw2">var</span> <span class="re0">$query</span>; <span class="co1">// Query resource</span>
&nbsp;
    <span class="co1">//! A constructor.</span>
    <span class="coMULTI">/**
    * Constucts a new DataAccess object
    * @param $host string hostname for dbserver
    * @param $user string dbserver user
    * @param $pass string dbserver user password
    * @param $db string database name
    */</span>
    <span class="kw2">function</span> DataAccess <span class="br0">(</span><span class="re0">$host</span>,<span class="re0">$user</span>,<span class="re0">$pass</span>,<span class="re0">$db</span><span class="br0">)</span> <span class="br0">{</span>
        <span class="re0">$this</span>-&gt;<span class="me1">db</span>=<a href="http://www.php.net/mysql_pconnect"><span class="kw3">mysql_pconnect</span></a><span class="br0">(</span><span class="re0">$host</span>,<span class="re0">$user</span>,<span class="re0">$pass</span><span class="br0">)</span>;
        <a href="http://www.php.net/mysql_select_db"><span class="kw3">mysql_select_db</span></a><span class="br0">(</span><span class="re0">$db</span>,<span class="re0">$this</span>-&gt;<span class="me1">db</span><span class="br0">)</span>;
    <span class="br0">}</span>
&nbsp;
    <span class="co1">//! An accessor</span>
    <span class="coMULTI">/**
    * Fetches a query resources and stores it in a local member
    * @param $sql string the database query to run
    * @return void
    */</span>
    <span class="kw2">function</span> fetch<span class="br0">(</span><span class="re0">$sql</span><span class="br0">)</span> <span class="br0">{</span>
        <span class="re0">$this</span>-&gt;<span class="me1">query</span>=<a href="http://www.php.net/mysql_unbuffered_query"><span class="kw3">mysql_unbuffered_query</span></a><span class="br0">(</span><span class="re0">$sql</span>,<span class="re0">$this</span>-&gt;<span class="me1">db</span><span class="br0">)</span>; <span class="co1">// Perform query here</span>
    <span class="br0">}</span>
&nbsp;
    <span class="co1">//! An accessor</span>
    <span class="coMULTI">/**
    * Returns an associative array of a query row
    * @return mixed
    */</span>
    <span class="kw2">function</span> getRow <span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span>
        <span class="kw1">if</span> <span class="br0">(</span> <span class="re0">$row</span>=<a href="http://www.php.net/mysql_fetch_array"><span class="kw3">mysql_fetch_array</span></a><span class="br0">(</span><span class="re0">$this</span>-&gt;<span class="me1">query</span>,MYSQL_ASSOC<span class="br0">)</span> <span class="br0">)</span>
            <span class="kw1">return</span> <span class="re0">$row</span>;
        <span class="kw1">else</span>
            <span class="kw1">return</span> <span class="kw2">false</span>;
    <span class="br0">}</span>
<span class="br0">}</span>
<span class="kw2">?&gt;</span></pre>
<p>
On top of this be place the Model;
</p>
<pre class="code php"><span class="kw2">&lt;?php</span>
<span class="coMULTI">/**
 *  Fetches "products" from the database
 */</span>
<span class="kw2">class</span> ProductModel <span class="br0">{</span>
    <span class="coMULTI">/**
    * Private
    * $dao an instance of the DataAccess class
    */</span>
    <span class="kw2">var</span> <span class="re0">$dao</span>;
&nbsp;
    <span class="co1">//! A constructor.</span>
    <span class="coMULTI">/**
    * Constucts a new ProductModel object
    * @param $dbobject an instance of the DataAccess class
    */</span>
    <span class="kw2">function</span> ProductModel <span class="br0">(</span>&amp;<span class="re0">$dao</span><span class="br0">)</span> <span class="br0">{</span>
        <span class="re0">$this</span>-&gt;<span class="me1">dao</span>=&amp; <span class="re0">$dao</span>;
    <span class="br0">}</span>
&nbsp;
    <span class="co1">//! A manipulator</span>
    <span class="coMULTI">/**
    * Tells the $dboject to store this query as a resource
    * @param $start the row to start from
    * @param $rows the number of rows to fetch
    * @return void
    */</span>
    <span class="kw2">function</span> listProducts<span class="br0">(</span><span class="re0">$start</span>=<span class="nu0">1</span>,<span class="re0">$rows</span>=<span class="nu0">50</span><span class="br0">)</span> <span class="br0">{</span>
        <span class="re0">$this</span>-&gt;<span class="me1">dao</span>-&gt;<span class="me1">fetch</span><span class="br0">(</span><span class="st0">"SELECT * FROM products LIMIT "</span>.<span class="re0">$start</span>.<span class="st0">", "</span>.<span class="re0">$rows</span><span class="br0">)</span>;
    <span class="br0">}</span>
&nbsp;
    <span class="co1">//! A manipulator</span>
    <span class="coMULTI">/**
    * Tells the $dboject to store this query as a resource
    * @param $id a primary key for a row
    * @return void
    */</span>
    <span class="kw2">function</span> listProduct<span class="br0">(</span><span class="re0">$id</span><span class="br0">)</span> <span class="br0">{</span>
        <span class="re0">$this</span>-&gt;<span class="me1">dao</span>-&gt;<span class="me1">fetch</span><span class="br0">(</span><span class="st0">"SELECT * FROM products WHERE PRODUCTID='"</span>.<span class="re0">$id</span>.<span class="st0">"'"</span><span class="br0">)</span>;
    <span class="br0">}</span>
&nbsp;
    <span class="co1">//! A manipulator</span>
    <span class="coMULTI">/**
    * Fetches a product as an associative array from the $dbobject
    * @return mixed
    */</span>
    <span class="kw2">function</span> getProduct<span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span>
        <span class="kw1">if</span> <span class="br0">(</span> <span class="re0">$product</span>=<span class="re0">$this</span>-&gt;<span class="me1">dao</span>-&gt;<span class="me1">getRow</span><span class="br0">(</span><span class="br0">)</span> <span class="br0">)</span>
            <span class="kw1">return</span> <span class="re0">$product</span>;
        <span class="kw1">else</span>
            <span class="kw1">return</span> <span class="kw2">false</span>;
    <span class="br0">}</span>
<span class="br0">}</span>
<span class="kw2">?&gt;</span></pre>
<p>
One thing to note is between the Model and the data access class, they 
never exchange more than a single row as an array - there’s no passing 
of multiple rows, which can serious slow an application down. The same 
applies to the class which uses the Model - it need only ever hold one 
row in memory - the rest is down to a stored query resource - in other 
words we leave to MySQL to hold the result for us.
</p>

<p>
Next the View - I’ve left out the <acronym title="HyperText Markup Language">HTML</acronym> to save space but you’ll find it in the complete code for this article.
</p>
<pre class="code php"><span class="kw2">&lt;?php</span>
<span class="coMULTI">/**
 *  Binds product data to HTML rendering
 */</span>
<span class="kw2">class</span> ProductView <span class="br0">{</span>
    <span class="coMULTI">/**
    * Private
    * $model an instance of the ProductModel class
    */</span>
    <span class="kw2">var</span> <span class="re0">$model</span>;
&nbsp;
    <span class="coMULTI">/**
    * Private
    * $output rendered HTML is stored here for display
    */</span>
    <span class="kw2">var</span> <span class="re0">$output</span>;
&nbsp;
    <span class="co1">//! A constructor.</span>
    <span class="coMULTI">/**
    * Constucts a new ProductView object
    * @param $model an instance of the ProductModel class
    */</span>
    <span class="kw2">function</span> ProductView <span class="br0">(</span>&amp;<span class="re0">$model</span><span class="br0">)</span> <span class="br0">{</span>
        <span class="re0">$this</span>-&gt;<span class="me1">model</span>=&amp; <span class="re0">$model</span>;
    <span class="br0">}</span>
&nbsp;
    <span class="co1">//! A manipulator</span>
    <span class="coMULTI">/**
    * Builds the top of an HTML page
    * @return void
    */</span>
    <span class="kw2">function</span> <a href="http://www.php.net/header"><span class="kw3">header</span></a> <span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span>
&nbsp;
    <span class="br0">}</span>
&nbsp;
    <span class="co1">//! A manipulator</span>
    <span class="coMULTI">/**
    * Builds the bottom of an HTML page
    * @return void
    */</span>
    <span class="kw2">function</span> footer <span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span>
&nbsp;
    <span class="br0">}</span>
&nbsp;
    <span class="co1">//! A manipulator</span>
    <span class="coMULTI">/**
    * Displays a single product
    * @return void
    */</span>
    <span class="kw2">function</span> productItem<span class="br0">(</span><span class="re0">$id</span>=<span class="nu0">1</span><span class="br0">)</span> <span class="br0">{</span>
        <span class="re0">$this</span>-&gt;<span class="me1">model</span>-&gt;<span class="me1">listProduct</span><span class="br0">(</span><span class="re0">$id</span><span class="br0">)</span>;
        <span class="kw1">while</span> <span class="br0">(</span> <span class="re0">$product</span>=<span class="re0">$this</span>-&gt;<span class="me1">model</span>-&gt;<span class="me1">getProduct</span><span class="br0">(</span><span class="br0">)</span> <span class="br0">)</span> <span class="br0">{</span>
             <span class="co1">// Bind data to HTML</span>
        <span class="br0">}</span>
    <span class="br0">}</span>
&nbsp;
    <span class="co1">//! A manipulator</span>
    <span class="coMULTI">/**
    * Builds a product table
    * @return void
    */</span>
    <span class="kw2">function</span> productTable<span class="br0">(</span><span class="re0">$rownum</span>=<span class="nu0">1</span><span class="br0">)</span> <span class="br0">{</span>
        <span class="re0">$rowsperpage</span>=<span class="st0">'20'</span>;
        <span class="re0">$this</span>-&gt;<span class="me1">model</span>-&gt;<span class="me1">listProducts</span><span class="br0">(</span><span class="re0">$rownum</span>,<span class="re0">$rowsperpage</span><span class="br0">)</span>;
        <span class="kw1">while</span> <span class="br0">(</span> <span class="re0">$product</span>=<span class="re0">$this</span>-&gt;<span class="me1">model</span>-&gt;<span class="me1">getProduct</span><span class="br0">(</span><span class="br0">)</span> <span class="br0">)</span> <span class="br0">{</span>
             <span class="co1">// Bind data to HTML</span>
        <span class="br0">}</span>
    <span class="br0">}</span>
&nbsp;
    <span class="co1">//! An accessor</span>
    <span class="coMULTI">/**
    * Returns the rendered HTML
    * @return string
    */</span>
    <span class="kw2">function</span> display <span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span>
        <span class="kw1">return</span> <span class="re0">$this</span>-&gt;<span class="me1">output</span>;
    <span class="br0">}</span>
<span class="br0">}</span>
<span class="kw2">?&gt;</span></pre>
<p>
And finally the Controller, which we’ll have implement the View as a child;
</p>
<pre class="code php"><span class="kw2">&lt;?php</span>
<span class="coMULTI">/**
 *  Controls the application
 */</span>
<span class="kw2">class</span> ProductController extends ProductView <span class="br0">{</span>
&nbsp;
    <span class="co1">//! A constructor.</span>
    <span class="coMULTI">/**
    * Constucts a new ProductController object
    * @param $model an instance of the ProductModel class
    * @param $getvars the incoming HTTP GET method variables
    */</span>
    <span class="kw2">function</span> ProductController <span class="br0">(</span>&amp;<span class="re0">$model</span>,<span class="re0">$getvars</span>=<span class="kw2">null</span><span class="br0">)</span> <span class="br0">{</span>
        ProductView::<span class="me2">ProductView</span><span class="br0">(</span><span class="re0">$model</span><span class="br0">)</span>;
        <span class="re0">$this</span>-&gt;<span class="me1">header</span><span class="br0">(</span><span class="br0">)</span>;
        <span class="kw1">switch</span> <span class="br0">(</span> <span class="re0">$getvars</span><span class="br0">[</span><span class="st0">'view'</span><span class="br0">]</span> <span class="br0">)</span> <span class="br0">{</span>
            <span class="kw1">case</span> <span class="st0">"product"</span>:
                <span class="re0">$this</span>-&gt;<span class="me1">productItem</span><span class="br0">(</span><span class="re0">$getvars</span><span class="br0">[</span><span class="st0">'id'</span><span class="br0">]</span><span class="br0">)</span>;
                <span class="kw1">break</span>;
            <span class="kw2">default</span>:
                <span class="kw1">if</span> <span class="br0">(</span> <a href="http://www.php.net/empty"><span class="kw3">empty</span></a> <span class="br0">(</span><span class="re0">$getvars</span><span class="br0">[</span><span class="st0">'rownum'</span><span class="br0">]</span><span class="br0">)</span> <span class="br0">)</span> <span class="br0">{</span>
                    <span class="re0">$this</span>-&gt;<span class="me1">productTable</span><span class="br0">(</span><span class="br0">)</span>;
                <span class="br0">}</span> <span class="kw1">else</span> <span class="br0">{</span>
                    <span class="re0">$this</span>-&gt;<span class="me1">productTable</span><span class="br0">(</span><span class="re0">$getvars</span><span class="br0">[</span><span class="st0">'rownum'</span><span class="br0">]</span><span class="br0">)</span>;
                <span class="br0">}</span>
                <span class="kw1">break</span>;
        <span class="br0">}</span>
        <span class="re0">$this</span>-&gt;<span class="me1">footer</span><span class="br0">(</span><span class="br0">)</span>;
    <span class="br0">}</span>
<span class="br0">}</span>
<span class="kw2">?&gt;</span></pre>
<p>
<a href="http://www.phppatterns.com/lib/exe/detail.php/design/archive/mvc.gif?id=design%3Aarchive%3Amodel_view_controller_pattern&amp;cache=cache" class="media" title="design:archive:mvc.gif"><img src="model_view_controller_pattern_files/mvc.gif" class="media" alt="" width="200" height="118"></a>
</p>

<p>
Note that this is not the only way to relate the classes in an MCV 
pattern - you might choose to have the controller implement the Model 
while aggregating the View, for example. This is just one approach which
 demonstrates the pattern.
</p>

<p>
Our index.php looks like this;
</p>
<pre class="code">&lt;?php
require_once('lib/DataAccess.php');
require_once('lib/ProductModel.php');
require_once('lib/ProductView.php');
require_once('lib/ProductController.php');

$dao=&amp; new DataAccess ('localhost','user','pass','dbname');
$productModel=&amp; new ProductModel($dao);
$productController=&amp; new ProductController($productModel,$_GET);
echo $productController-&gt;display();
?&gt;
</pre>

<p>
Nice and simple.
</p>

<p>
We could have been more cunning with the controller it’s worth noting. With <acronym title="Hypertext Preprocessor">PHP</acronym> you can pull stunts like this;
</p>
<pre class="code">$this-&gt;{$_GET['method']}($_GET['param']);
</pre>

<p>
What that approach suggests is you need to define your applications <acronym title="Uniform Resource Locator">URL</acronym> namespace doing so that it conforms to a standard such as:
</p>

<p>
“index.php?class=ProductView&amp;method=productItem&amp;id=4”
</p>

<p>
Using that we could do the following in our controller;
</p>
<pre class="code php"><span class="re0">$view</span>=<span class="kw2">new</span> <span class="re0">$_GET</span><span class="br0">[</span><span class="st0">'class'</span><span class="br0">]</span>;
<span class="re0">$view</span>-&gt;<span class="br0">{</span><span class="re0">$_GET</span><span class="br0">[</span><span class="st0">'method'</span><span class="br0">]</span><span class="br0">(</span><span class="re0">$_GET</span><span class="br0">[</span><span class="st0">'id'</span><span class="br0">]</span><span class="br0">)</span>;</pre>
<p>
In some ways, building the controller is the hardest part, when trying 
to balance rapid development with scalability. A good place to get 
inspiration is <a href="http://jakarta.apache.org/struts/userGuide/building_controller.html" class="urlextern" title="http://jakarta.apache.org/struts/userGuide/building_controller.html" rel="nofollow">Java Struts</a> by the Apache group, where your controller is essentially defined by <acronym title="Extensible Markup Language">XML</acronym> documents. 
</p>

</div>
<div class="footnotes">
<div class="fn"><a href="#fnt1" id="fn1" name="fn1" class="fn_bot">1)</a> 
<a href="http://www.phppatterns.com/lib/exe/fetch.php/design/archive/mvc.zip?id=design%3Aarchive%3Amodel_view_controller_pattern&amp;cache=cache" class="urlextern" title="design:archive:mvc.zip" style="background-image: url(http://www.phppatterns.com/lib/images/fileicons/zip.png)">Sample MCV Code</a>
</div>
</div>

<!-- cachefile /home/patterns/dw_data/cache/1/1928c94b8282502ea3822f57fa1e1b8d.xhtml used -->
						<div class="toplink">
				<a href="#top" class="action top" accesskey="x">Back to top</a>			</div>
			<hr>
			<div class="meta">
				design/archive/model_view_controller_pattern.txt · Last modified: 2005/10/15 21:47			</div>
		</div>
	</div>
	<div id="sidebar">
		<div class="sidebox">
			<div class="sidebox_title">
				indexes
			</div>
			<div class="sidebox_content">
					<ul>
						<li> → <a href="http://www.phppatterns.com/docs/about/phppatterns">about:site</a></li>
						<li> → <a href="http://www.phppatterns.com/docs/?idx=advocacy">advocacy</a></li>
						<li> → <a href="http://www.phppatterns.com/docs/?idx=blogs">blogs</a></li>
						<li> → <a href="http://www.phppatterns.com/docs/?idx=design">design</a></li>
						<li> → <a href="http://www.phppatterns.com/docs/?idx=develop">develop</a></li>
						<li> → <a href="http://www.phppatterns.com/docs/?idx=news">news</a></li>
						<li> → <a href="http://www.phppatterns.com/docs/?idx=reviews">reviews</a></li>
						<li> → <a href="http://www.phppatterns.com/docs/?idx=wiki">wiki</a>:<a href="http://www.phppatterns.com/docs/wiki/syntax">syntax</a></li>
					</ul>
			</div>
					</div>
		<div class="user">
					</div>
		<div class="footerinc" align="center">
			<a target="_blank" href="http://www.phppatterns.com/feed.php" title="">
				<img src="model_view_controller_pattern_files/button-rss.png" alt="" width="80" border="0" height="15">
			</a>
			<a target="_blank" href="http://creativecommons.org/licenses/by-nc-sa/2.0/" rel="license" title="">
				<img src="model_view_controller_pattern_files/button-cc.gif" alt="" width="80" border="0" height="15">
			</a>
			<a target="_blank" href="http://www.procata.com/blog/" title="Professional PHP Blog">
				<img src="model_view_controller_pattern_files/prophp-blog.png" alt="Professional PHP Blog" border="0">
			</a>
			<a target="_blank" href="http://www.php.net/" title="">
				<img src="model_view_controller_pattern_files/button-php.gif" alt="" width="80" border="0" height="15">
			</a>
			
			<a target="_blank" href="http://validator.w3.org/check/referer" title="">
				<img src="model_view_controller_pattern_files/button-xhtml.png" alt="" width="80" border="0" height="15">
			</a>
			<a target="_blank" href="http://jigsaw.w3.org/css-validator/check/referer" title="">
				<img src="model_view_controller_pattern_files/button-css.png" alt="" width="80" border="0" height="15">
			</a>
			<a target="_blank" href="http://wiki.splitbrain.org/wiki:dokuwiki" title="">
				<img src="model_view_controller_pattern_files/button-dw.png" alt="" width="80" border="0" height="15">
			</a>
                        <a target="_blank" href="http://www.planet-php.net/" title="Planet PHP">
                                <img src="model_view_controller_pattern_files/planet-php.jpg" alt="Planet PHP" width="80" border="0" height="15">
                        </a>
						
		</div>
	</div>
	</div>


</body><lcs_336d0c35_8a85_403a_b9d2_65c292c39087_dataexchangeelement action="" valueresult="" valuename=""></lcs_336d0c35_8a85_403a_b9d2_65c292c39087_dataexchangeelement></html>